<?php
include_once(_APP_PATH. "business/media/media_handler.php");
class MediaHandlerVideo extends MediaHandler
{
	private $_fileObj;	
	
	protected function InitFile()
	{
		$this->_fileObj = new ffmpeg_movie($this->_filePath);
		if (!$this->_fileObj || !$this->_fileObj->hasVideo() || !$this->_fileObj->getDuration())	
		{
			$this->SetError('В файле не найден видео поток');
		}
		
		$this->_fileSize = filesize($this->_filePath);
		$this->_fileLength = $this->_fileObj->getDuration();		
	}
	
	public function CreateThumbNail()
	{
		if (false === $this->_fileThumbNail)
		{
			$this->_fileThumbNail = '';	
			
			$destPath = $this->GetDestPath();
			if (false === $destPath) return false;			
			
			$frameCount = (int)$this->_fileObj->getFrameCount();
			if ($frameCount)
			{
				$frame = $this->_fileObj->getFrame(ceil($frameCount / 2));
				if ($frame)
				{
					$image = $frame->toGDImage();
					if ($image)
					{	
						$filename = pathinfo($this->_filePath, PATHINFO_FILENAME);
						$thumbPath = $destPath.$filename. '-thumb.jpg';
						@ImageJpeg($image, $thumbPath, 90);
						@ImageDestroy($image);
						
						if (is_file($thumbPath))
						{
							$this->_fileThumbNail = $thumbPath;	
						}
					}
				}
			}	

			if ('' === $this->_fileThumbNail)
			{
				$this->_fileThumbNail = _ROOT_PATH.MozgCfg::GetProp('global/media//mediaImageFolder').MozgCfg::GetProp('global/media//defaultVideoThumbNail');
			}			
		}

		return $this->_fileThumbNail;
	}	
	
	public function Convert($code)
	{
		$destPath = $this->GetDestPath();
		if (false === $destPath) 
		{
			$this->SetConvertStatus(MatchMediaStatus::HasError);
			$this->SetError('Произошла ошибка при обработке файла');
			return false;
		}		

		$fileInfo = pathinfo($this->GetFilePath());
		$destFile = $destPath.$fileInfo['filename']. '.flv';		
		$newSize = implode('x', $this->GetNewSize($this->_fileObj->getFrameWidth(), $this->_fileObj->getFrameHeight()));

		$command = 'ffmpeg -y -i %1$s -acodec libmp3lame -s ' .$newSize. ' -ar 44100 -vcodec flv %2$s';		
		$result = $this->RunShellCommand($command, $destFile, $code);
		if (!$result) 
		{
			$this->SetConvertStatus(MatchMediaStatus::HasError);
			$this->SetError('Произошла ошибка при обработке файла');
			return false;
		}	
		
		$this->SetConvertStatus(MatchMediaStatus::NotProcessed);
		
		return $destFile;
	}
	
	private function GetNewSize($width, $height)
	{
		list($maxWidth, $maxHeight) = MozgCfg::GetProp('global/media//videoSizeTo');
		 
		$diffX = max($width - $maxWidth, 0);
		$diffY = max($height - $maxHeight, 0);
		if ($diffX < $diffY)
		{
			$tnHeight = $height - $diffY;
			
			$ratio = $tnHeight/$height;
			$tnWidth = ceil($ratio*$width);											
		}
		else
		{
			$tnWidth = $width - $diffX;
			
			$ratio = $tnWidth/$width;
			$tnHeight = ceil($ratio*$height);			
		}	

		return array($tnWidth, $tnHeight);
	}
}